package com.bsj.travel.handler;

import com.bsj.travel.def.global.JsonResult;
import com.bsj.travel.def.global.JsonResultEnum;
import com.bsj.travel.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author yinhao
 * @version 1.0
 * @description 网关异常统一处理
 * @date 2022/9/14
 */
@Order(-1)
@Configuration
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        JsonResult result = null;
        if (ex instanceof NotFoundException) {
            result = JsonResult.fail(JsonResultEnum.SERVER_NOT_FOUND);
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            result = JsonResult.success(200, responseStatusException.getMessage());
        } else {
            result = JsonResult.fail(JsonResultEnum.RUNTIME_EXCEPTION);
        }
        log.error("[网关异常处理]请求路径：{},异常信息：{}", exchange.getRequest().getPath(), ex.getMessage());
            return ServletUtils.webFluxResponseWriter(response, result);
    }
}
